#!/bin/bash
# gaureopt
# written by zhongcheng@whu.edu.cn
# contact me if you have any suggestings or find bugs
# QQ:32589927

function helpfunc() {
    echo 'gaureopt: resubmit g16 opt job with modified keywords'
    echo 'requies: qcinp.py g16s'
    echo 'usage: gaureopt *.log to check all job terminated with L9999 and resubmit'
    echo 'usage: gaureopt slurm_jobid to resubmit job with slurm job id'
    echo 'usage: gaureopt dir to check all log file in that dir and resubmit file terminated with L9999'
    echo '       -[i set job id to submit]'
    echo '       -[d set dir, the log under which will be check and submit if needed]'
    echo '       -[a set added keywords, default is opt(maxstep=2,notrust)]'
    exit 1
}
if [ $# -lt 1 ]; then
    helpfunc
fi
while getopts ":i:d:a:" opt
do
    case $opt in
        i) jobid=$OPTARG;;
        d) checkdir=$OPTARG;;
        a) addkeywords=$OPTARG;;
        ?) helpfunc;;
    esac
done
shift $(($OPTIND - 1))

if ! command -v qcinp.py > /dev/null 2>&1;then
   echo "qcinp.py not in PATH, you could obtain it in https://gitee.com/coordmagic/coordmagic"
   echo "new gjf will not be generated"
else
   QCINP=qcinp.py
fi
if ! command -v g16s > /dev/null 2>&1;then
    echo "g16s not in PATH, you could obtain it in https://gitee.com/coordmagic/ztools"
    echo "The job will not be submitted automatically"
else
    G16S=g16s
fi
    

if [[ -z $addkeywords ]];then
    addkeywords="opt(maxstep=2,notrust)"
fi

if [[ -n $jobid ]];then
    for i in $jobid;do
        wd=`squeue -o "%8i %20j %Z" | awk -v id=$i '{if($1==id)print $3}'`
        basename=`squeue -o "%8i %20j %Z" | awk -v id=$i '{if($1==id)print $2}'`
        cd  $wd
        scancel $i
        if [[ -n $QCINP ]];then
            qcinp.py -a "$addkeywords" ${basename}.log
            if [[ -n $G16S ]];then
                g16s ${basename}.gjf
            fi
        fi
    done
fi
while [[ $# -ge 1 ]]
do
    if [[ -f "$1" && "${1: -4}" == ".log" ]]; then
        eflag=`grep "Error termination request processed by link 9999" $1`
        if [ -n "$eflag" ];then
            echo "Error termination link 9999 in $1"
            if [[ -n $QCINP ]];then
                qcinp.py -a "$addkeywords" $1
                if [[ -n $G16S ]];then
                    g16s ${1/.log/}.gjf
                fi
            fi
        fi
    elif [[ -d "$1" ]]; then
        cd $1
        for i in *.log;do
            eflag=`grep "Error termination request processed by link 9999" $i`
            if [ -n "$eflag" ];then
                echo "Error termination link 9999 in ${1}/$i"
                if [[ -n $QCINP ]];then
                    qcinp.py -a "$addkeywords" $i
                    if [[ -n $G16S ]];then
                        g16s ${i/.log/}.gjf
                    fi
                fi
            fi
        done
    fi            
shift 1
done
        
